<?php
class verifyCodeClaim
{
	/* 
	 * 返回验证码是否有效
	*/
	public static function verify($code) { 
		$VerifyCode = M("module_verify_code");
		$condition['code'] = array('eq',$code);
		$result = $VerifyCode->where($condition)->find();
			Log::write('verify find sql is:'.$VerifyCode->getLastSql());
		if ($result) {
			
			if ($VerifyCode->where($condition)->getField('isClaim') == 0) {
				Output::instance()->resultCode(code_success);
				return code_success;
			} else {
				$msg = '奖品已领取';
				Output::instance()->resultCode(code_custom_error, $msg);
				return code_verifycode_claimed;
			}
		} else {
			$msg = '无效的验证码';
			Output::instance()->resultCode(code_custom_error, $msg);
			return code_verifycode_notexist;
		}
		
	}
	
	public static function claim($code, $branch) {
		$time = date("Y-m-d H:i:s");
		$VerifyCode = M("module_verify_code");
		
		$condition['code'] = array('eq',$code);
		$verifyCode = $VerifyCode->where($condition)->find();
		if ($verifyCode) {
			
			if($verifyCode['validate'] == 1){
				$validateEndTime = $verifyCode['validateEndTime'];
				if($validateEndTime != NULL){
					if(strtotime($time) >strtotime($validateEndTime)){
						$msg = '验证码已过期';
						Output::instance()->resultCode(code_custom_error, $msg);
						return code_red_envelope_verify_code_has_expire;
					}
				}
			}
				

			$data['isClaim'] = 1;
			$data['branch'] = $branch;
			$data['claimTime'] = $time;
			$ret = $VerifyCode->where($condition)->save($data);
			
// 			$ret = $VerifyCode->where($condition)->setField('isClaim', 1);
			
			if ($ret) {
				// 使用和claimModule中同样的方式处理字符串，删掉用户名中空格回车等字符
// 				$arr = explode("wx",$branch);
// 				$branch = 'wx' . ((int)$arr[1]);
// 				$VerifyCode->where("code='$code'")->setField('branch', $branch);
// 				$VerifyCode->where("code='$code'")->setField('claimTime', date('Y-m-d H:i:s'));
				Output::instance()->resultCode(code_success);
				return code_success;
			} else {
				$msg = '领取失败';
				Output::instance()->resultCode(code_custom_error, $msg);
				return code_verifycode_claimed;
			}
		} else {
			$msg = '无效的验证码';
			Output::instance()->resultCode(code_custom_error, $msg);
			return code_verifycode_notexist;
		}
	}
}